package com.rk.kbk.common;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/9.
 */
@Service
public class SqlToResult {
    @PersistenceContext
    private EntityManager em;

    public Object getResultList(String sql, String oneOrMany){
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Object> lo = new ArrayList<>();
        query.getResultList().forEach(n -> lo.add(PubLib.convert(n)));
        if (oneOrMany != null && oneOrMany.equals("one")) {
            if (lo.isEmpty()) {
                return null;
            }
            return lo.get(0);
        }
        return lo;
    }

    public Object getResultList(String sql){
        return getResultList(sql, null);
    }

}
